<template>
  <div class="app-container">
    <el-form
      :inline="true"
    >
      <el-form-item>
        <input
          type="file"
          @change="jsReadFiles"
        >
      </el-form-item>
      <el-form-item>
        <el-button
          icon="el-icon-plus"
          type="primary"
          @click="showAdd"
        >{{ $t('add') }}</el-button>
      </el-form-item>
    </el-form>

    <el-table
      :data="productList"
      style="width: 100%;margin-bottom: 20px"
      @row-click="manage"
    >
      <el-table-column
        prop="productId"
        :label="$t('id')"
        width="80"
      />
      <el-table-column prop="productId" :label="$t('icon')" width="80">
        <template slot-scope="scope">
          <img
            :src="scope.row.iconUrl"
            style="width: 35px;height: 35px"
          >
        </template>
      </el-table-column>
      <el-table-column :label="$t('name')">
        <template slot-scope="scope">
          <span @click.stop="dictionaries(scope.row)">{{ scope.row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="keyName" :label="$t('keyName')" />
      <el-table-column prop="remark" :label="$t('remark')" />
      <el-table-column
        prop="createdDate"
        :label="$t('createdDate')"
        sortable
        width="200"
      >
        <template slot-scope="scope">
          <i class="el-icon-time" />
          <span style="margin-left: 13px">{{ formatDate(scope.row.createdDate) }}</span>
        </template>
      </el-table-column>
      <el-table-column width="240" :label="$t('function')">
        <template slot-scope="scope">
          <el-button
            type="text"
            icon="el-icon-download"
            @click.stop="exportProduct(scope.row)"
          >{{ $t('download') }}
          </el-button>
          <el-button
            type="text"
            icon="el-icon-edit"
            @click.stop="edit(scope.row)"
          >{{ $t('edit') }}
          </el-button>
          <el-button
            type="text"
            style="color: #FF805F"
            icon="el-icon-delete"
            @click.stop="del(scope.row)"
          >{{ $t('delete') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div
      style="margin: 15px 0;text-align: right;"
    >
      <el-pagination
        background
        :current-page.sync="currentPage"
        :page-size="pageSize"
        layout="total,sizes,prev,pager,next,jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <el-dialog
      :visible.sync="dialogProductFormVisible"
    >
      <el-form :model="product">
        <el-form-item :label="$t('name')">
          <el-input
            v-model="product.name"
            :disabled="model=='update'"
          />
        </el-form-item>
        <el-form-item :label="$t('keyName')">
          <el-input
            v-model="product.keyName"
            :disabled="model=='update'"
          />
        </el-form-item>
        <el-form-item :label="$t('remark')">
          <el-input v-model="product.productDesc" />
        </el-form-item>
        <el-form-item :label="$t('icon')">
          <el-input v-model="product.iconUrl">
            <template slot="prepend">
              <el-image
                style="width: 20px;height: 20px;margin-top: 2px"
                :src="product.iconUrl"
              />
            </template>
            <template slot="append">
              <i class="el-icon-caret-bottom" @click="choseIcon" />
            </template>
          </el-input>
          <div v-show="isIconOpen">
            <el-image
              v-for="(item,index) in iconList"
              :key="index"
              style="margin: 5px;cursor: pointer;width: 40px;height: 40px"
              :src="item.url"
              @click="changeIco(item.url,200145308)"
            />
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogProductFormVisible = false">{{ $t("cancel") }}</el-button>
        <el-button type="primary" @click="addOrUpdateProduct">{{ $t("confirm") }}</el-button>
      </div>
    </el-dialog>

    <el-dialog
      :visible.sync="dialogProductDictionariesVisible"
    >
      <dictionaries-model
        v-if="dialogProductDictionariesVisible"
        :product-id="product.productId"
        template-type="product"
        :key-name="product.keyName"
      />
    </el-dialog>

    <el-dialog
      :visible.sync="dialogImportProductFormVisible"
    >
      <el-form>
        <el-form-item :label="$t('config')">
          <el-input
            v-model="importProductConfig"
            type="textarea"
            :rows="20"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogImportProductFormVisible = false">{{ $t("cancel") }}</el-button>
        <el-button type="primary" @click="importProduct">{{ $t("confirm") }}</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import DictionariesModel from '../info/components/DictionariesModel'
import {
  formatDate,
  successNotice,
  cancelNotice
} from '@/util/common'
import {
  pageGetProduct,
  updateProduct,
  insertProduct,
  deleteProductList,
  listProductIcon,
  exportProduct,
  importProduct
} from '@/api/iot/iotProductApi'
import {
  getPageSize,
  setPageSize,
  getCompanyId
} from '@/util/storage'
import { downloadStr } from '@/util/file'
export default {
  name: 'ProductManage',
  components: {
    DictionariesModel
  },
  data() {
    return {
      importProductConfig: '',
      dialogImportProductFormVisible: false,
      dialogProductDictionariesVisible: false,
      currentPage: 1,
      total: 0,
      pageSize: getPageSize(),
      productList: [],
      dialogProductFormVisible: false,

      product: {
        name: null,
        productDesc: null,
        productId: null,
        iconUrl: null
      },
      companyId: getCompanyId(),
      iconList: [],
      isIconOpen: false
    }
  },
  mounted() {
    this.listProductIcon()
    this.pageGetProduct()
  },
  methods: {
    importProduct() {
      importProduct(JSON.parse(this.importProductConfig)).then(res => {
        const { code } = res
        if (code === '200') {
          successNotice(this)
          this.dialogImportProductFormVisible = false
          this.pageGetProduct()
        }
      })
    },
    jsReadFiles(e) {
      const that = this
      if (e.target.files.length) {
        const file = e.target.files[0]
        const reader = new FileReader()// new一个FileReader实例
        // if (/text+/.test(file.type)) { // 判断文件类型，是不是text类型
        reader.onloadend = function(e) {
          that.importProductConfig = e.target.result
          that.dialogImportProductFormVisible = true
        }
        reader.readAsText(file)
        // }
      }
    },
    choseIcon() {
      if (this.isIconOpen) {
        this.isIconOpen = false
      } else {
        this.isIconOpen = true
      }
    },
    changeIco(iconUrl) {
      this.isIconOpen = false
      this.product.iconUrl = iconUrl
    },
    listProductIcon() {
      listProductIcon({
      }).then(res => {
        const { code, data } = res
        if (code === '200') {
          this.iconList = data
        }
      })
    },
    dictionaries(item) {
      this.product = item
      this.dialogProductDictionariesVisible = true
    },
    formatDate(time) {
      return formatDate(this, time)
    },
    handleSizeChange(val) {
      this.pageSize = val
      setPageSize(this.pageSize)
      this.pageGetProduct()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.pageGetProduct()
    },
    addOrUpdateProduct() {
      const data = {
        keyName: this.product.keyName,
        remark: this.product.productDesc,
        iconUrl: this.product.iconUrl,
        name: this.product.name
      }
      if (this.product.productId) {
        data.productId = this.product.productId
        updateProduct(data).then(res => {
          const { code } = res
          if (code === '200') {
            successNotice(this)
            this.pageGetProduct()
          }
        })
      } else {
        insertProduct(data).then(res => {
          const { code } = res
          if (code === '200') {
            successNotice(this)
            this.pageGetProduct()
          }
        })
      }
    },

    pageGetProduct() {
      pageGetProduct({
        companyId: this.companyId,
        pageSize: this.pageSize,
        currentPage: this.currentPage
      }).then(res => {
        const { code, data } = res
        if (code === '200') {
          this.total = data.total
          this.productList = data.data
        }
      })
    },
    showAdd() {
      this.product = {}

      this.dialogProductFormVisible = true
    },
    exportProduct(item) {
      exportProduct({
        productId: item.productId
      }).then(res => {
        const { code, data } = res
        if (code === '200') {
          downloadStr(item.name + '.json', JSON.stringify(data))
        }
      })
    },
    edit(item) {
      this.product = item

      this.dialogProductFormVisible = true
    },
    manage(item) {
      this.$router.push({
        path: '/product/info/' + item.productId,
        query: { productId: item.productId, name: item.name, keyName: item.keyName }
      })
    },
    del(index) {
      const that = this
      this.$confirm(this.$t('delete') + index.name, this.$t('prompt'), {
        confirmButtonText: this.$t('confirm'),
        cancelButtonText: this.$t('cancel'),
        type: 'warning'
      })
        .then(function() {
          deleteProductList({
            idList: [index.productId]
          }).then(res => {
            const { code } = res
            if (code === '200') {
              successNotice(that)
              that.pageGetProduct()
            }
          })
        })
        .catch(function() {
          cancelNotice(that)
        })
    }
  }
}
</script>
<style scoped lang="scss">
  @import '@/styles/element-variables.scss';

  .primary-color {
    color: $--color-primary;
  }

  .el-icon-arrow-down {
    font-size: 12px;
  }

</style>
